package com.main.locatme;

import android.os.AsyncTask;
import android.util.Log;
import android.widget.ArrayAdapter;

import com.locatme.fragment.EventsFragment;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.ArrayList;

/**
 * Created by Julien on 29/03/14.
 */
public class GetPlaces extends AsyncTask<String, Void, ArrayList<String>> {
        private EventsFragment activity;

    public GetPlaces(EventsFragment activity) {
        this.activity = activity;
    }

    @Override
    protected ArrayList<String> doInBackground(String... args) {


        ArrayList<String> predictionsArr = new ArrayList<String>();

        try {

            URL googlePlaces = new URL(
                    "https://maps.googleapis.com/maps/api/place/autocomplete/json?input=" + URLEncoder.encode(args[0].toString(), "UTF-8") + "&types=geocode&language=en&sensor=true&key=AIzaSyB_fFrc4iHchdDP1t2yLLcEpGdwdMAVucw");
            URLConnection tc = googlePlaces.openConnection();
            BufferedReader in = new BufferedReader(new InputStreamReader(
                    tc.getInputStream()));

            String line;
            StringBuffer sb = new StringBuffer();
            //Récupérer la réponse de Google Places et la convertir en String.
            while ((line = in.readLine()) != null) {
                sb.append(line);
            }
            //Trasformer la chaine de cararactère en objet  JSON
            JSONObject predictions = new JSONObject(sb.toString());
            //récupérer le champ prédiction du JSON
            JSONArray ja = new JSONArray(predictions.getString("predictions"));

            for (int i = 0; i < ja.length(); i++) {
                JSONObject jo = (JSONObject) ja.get(i);
                //ajouter chaque predictions à l'arrayList
                predictionsArr.add(jo.getString("description"));
            }
        } catch (IOException e) {

            Log.e("myapp", "GetPlaces : doInBackground", e);

        } catch (JSONException e) {

            Log.e("myapp", "GetPlaces : doInBackground", e);

        }

        return predictionsArr;

    }


    @Override
    protected void onPostExecute(ArrayList<String> result) {

        //mettre à jour l'adapteur
        activity.adapterAutoComplete = new ArrayAdapter<String>(activity.getActivity().getBaseContext(), R.layout.itemautocompletelist,R.id.itemList);
        activity.adapterAutoComplete.setNotifyOnChange(true);
        //attacher l'adapteur à la TextView
        activity.userInputadr.setAdapter(activity.adapterAutoComplete);

        for (String string : result) {

            activity.adapterAutoComplete.add(string);
            activity.adapterAutoComplete.notifyDataSetChanged();

        }

    }

}
